<?php

namespace app\api\service;

use think\Controller;
use think\Db;

class Registration extends Controller
{
	protected static $err_code = 0;

	// 签到接口
	public static function index_registration($param) {
		try {
			$registration['days'] = model('registration')->where('member_id', $param['member_id'])->count();
			$registration['clothes_money'] = model('member')->where('id', $param['member_id'])->value('clothes_money');
			$registration['is_registration'] = self::check_registration($param);
			return api_return(200, $registration);
		} catch (\Exception $e) {
			return api_return(0, [], $e->getMessage());
		}
	}

	// 签到接口
	public static function save_registration($param) {
		// 启动事务
		Db::startTrans();
		try {
			// 添加签到记录
			$data = ['member_id' => $param['member_id'], 'create_time' => strtotime(date('Y-m-d'))];
			model('registration')->save($data);
			
			// 签到成功 赠送衣币
			$integral_data = ['member_id' => $param['member_id'], 'money' => 1, 'msg' => '签到赠送'];
			model('clothes_money_bill')->save($integral_data);
			
			// 更新用户表
			model('member')->where('id', $param['member_id'])->setInc('clothes_money', 1);
			
			// 提交事务
			Db::commit();
			return api_return(200, []);
		} catch (\Exception $e) {
			// 回滚事务
			Db::rollback();
			return api_return(200, [], $e->getMessage());
		}
	}

	// 检查当天是否已经签到接口接口
	public static function check_registration($param)
	{
		try
		{
			// 检查该用户是否已经签到，虽然前端会做判断，但是还是要以防万一
			$registration_time = strtotime(date('Y-m-d'));
			$check_registration = model('registration')->where('create_time', $registration_time)->where('member_id', $param['member_id'])->find();
			if ($check_registration)
			{
				throw new \Exception('已签到');
			}
			return api_return(200, []);
		}
		catch (\Exception $e)
		{
			return api_return(0, [], $e->getMessage());
		}
	}

	// 获取签到明细列表
	public static function get_sign_in_list($param)
	{
		try
		{
			$where['member_id'] = $param['member_id'];
			$member_registration_list = model('registration')->where($where)->order('create_time desc')->paginate();
			return api_return(200, $member_registration_list);
		}
		catch (\Exception $e)
		{
			return api_return(0, [], $e->getMessage());
		}
	}
}
